<template>
  <div>
    <el-table-form ref="form" class="form" :model="query">
      <el-form-item label="安检时间:" :table-form-merge="2">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 180px; margin-right: 2px;">
          <el-option label="安检单号" value="checkId" />
          <el-option label="订单号" value="orderCode" />
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="客户地址" value="csmAddress" />
        </el-select>
        <el-input v-model.trim="param" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select
          v-model="query.csmTypes"
          clearable
          placeholder="请选择"
          @change="changType"
        >
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用气性质:" prop="csmItem">
        <el-select
          v-model="query.subType"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in subTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="隐患等级:" prop="warnLevel">
        <el-select v-model="query.warnLevel" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in warnLevelMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="标签:" prop="labelSource">
        <el-select v-model="query.labelSource" multiple filterable clearable placeholder="请选择">
          <el-option
            v-for="item in labelMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="所属机构:" prop="orgSNNo">
        <!-- <el-select v-model="query.orgType" style="width: 180px; margin-right: 2px;">
          <el-option label="安检人机构" value="security" />
          <el-option label="责任机构" value="guarantee" />
        </el-select> -->
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="0.2">
        <el-checkbox v-model="query.option" label="包含下级" />
      </el-form-item>
      <el-form-item label="安检人:" prop="checkUserIdList">
        <el-select v-model="query.checkUserIdList" filterable clearable multiple collapse-tags placeholder="请选择">
          <el-option
            v-for="item in checkUserMap"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="安检类型:">
        <el-select v-model="query.checkType" filterable clearable placeholder="请选择" @change="changeChecktype">
          <el-option
            v-for="item in checkTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="整改状态:" prop="repairStatus">
        <el-select v-model="query.repairStatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in checkStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="安检照片:" :table-form-merge="1" prop="imageName">
        <!-- <el-radio-group v-model="query.imageName" @change="radioChange">
          <el-radio label="all">全部</el-radio>
          <el-radio label="yes">有</el-radio>
          <el-radio label="no">无</el-radio>
        </el-radio-group> -->
        <el-select v-model="query.imageName" clearable placeholder="请选择" @change="radioChange">
          <el-option
            v-for="item in imageList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所在区域:" prop="area">
        <el-select v-model="query.countryCode" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in addressProps"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- <el-cascader ref="cascader" v-model="area" style="width: 100%;" :props="addressProps" clearable @change="areaChange" /> -->
      </el-form-item>
      <el-form-item label="安检单类别:">
        <el-select v-model="query.isAudit" clearable placeholder="请选择">
          <el-option
            v-for="item in isAuditMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="是否即查:">
        <el-select v-model="query.warnLevel" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in optionList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否即改:">
        <el-select v-model="query.warnLevel" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in optionList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否意向:">
        <el-select v-model="query.warnLevel" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in intentionList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <template v-slot:btns>
        <el-button
          v-permission="[60101, 1]"
          type="primary"
          icon="el-icon-search"
          :loading="$loadingPlugin.fetchData"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <el-button
        v-permission="[60101, 2]"
        type="primary"
        icon="el-icon-download"
        :loading="$loadingPlugin.batchExp"
        @click="batchExp"
      >导出</el-button>
      <!-- <el-button
        type="primary"
        icon="el-icon-s-platform"
        @click="batchExamine"
      >批量审核</el-button> -->
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      class="check-lbTable"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      :immediate-fetch="false"
      @fetch="fetchData"
      @selection-change="handleSelectionChange"
    />

    <securityOrderInfo
      ref="securityOrderInfo"
      :index-table-data="tableData.data"
      :warn-level-map="warnLevelMap"
      :tree-data="treeData"
      :parent-fetch-data="refresh"
    />
    <batchExamine ref="batchExamine" />
    <rectification ref="rectification" />
    <csm-detail ref="csmDetail" :parent-fetch-data="refresh" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
    <isIntention ref="isIntention" />
    <checkandFix ref="checkandFix" />
    <repairDetail ref="repairDetail" />
  </div>
</template>

<script>
  import { querySubTypeMap, getCustomerLabel, selectAreaCode } from '@/api'
  import rectification from './components/rectification.vue'
  import securityOrderInfo from './components/securityOrderInfo.vue'
  import batchExamine from './components/batchExamine.vue'
  import CsmDetail from '../../components/CsmDetailModal/index.vue'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import passed from '@/assets/passed.png'
  import danger from '@/assets/danger.png'
  import danger2 from '@/assets/danger2.png'
  import fixed from '@/assets/fixed.png'
  import checkandFix from './components/checkandFix'
  import isIntention from './components/isIntention'
  import {
    gasCheckBillQueryList,
    gasCheckBillExport,
    gasCheckBillReverse,
    gasCheckItemList,
    queryRiskTrackMap,
    csDeliverUserList,
    queryMap,
    queryTransactorList
  } from '@/api'
  import moment from 'dayjs'
  export default {
    name: 'securityOrderManage',
    components: {
      securityOrderInfo, batchExamine, rectification, CsmDetail, checkandFix, isIntention,
      OrderDetail: () => import('../../orderCenter/orderManage/components/OrderDetails.vue'),
      repairDetail: () => import('../../workOrderCenter/repairOrder/components/Detail.vue')
    },
    data() {
      return {
        qtype: 'checkId',
        param: '',
        actionColWidth: 80,
        mode: 1,
        treeData: [],
        gasCheckItemArray: [],
        txt: '',
        checkUserMap: [],
        multipleSelection: [],
        calcTypeList: [],
        paymenFilList: [],
        orderStatusMap: [],
        orderFlagMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        orderSourceMap: [],
        transactorList: [],
        customerTypeMap: [],
        labelMap: [
          { desc: '月度活跃', value: 4 },
          { desc: '季度活跃', value: 5 },
          { desc: '半年活跃', value: 6 },
          { desc: '沉睡', value: 2 },
          { desc: '休眠', value: 3 }
        ],
        subTypeList: [],
        subTypeAllList: [],
        checkTypeMap: [
          { value: 1, desc: '随单安检', key: 'SD' },
          { value: 2, desc: '定期安检', key: 'JH' }
        ],
        warnLevelMap: [],
        //   { value: -1, desc: '无隐患', key: 'ZOO' },
        //   { value: 1, desc: '一般隐患', key: 'YJ' },
        //   { value: 2, desc: '严重隐患', key: 'EJ' },
        //   { value: 3, desc: '隐患', key: 'SJ' },
        //   { value: 4, desc: '危险隐患', key: 'SIJ' },
        //   { value: 5, desc: '致命隐患', key: 'WJ' }
        checkStatusMap: [
          { value: 1, desc: '待整改', key: 'UN_rectification' },
          { value: 2, desc: '已整改', key: 'Rectification' }
        ],
        imageList: [
          { value: 'all', desc: '全部' },
          { value: 'yes', desc: '有' },
          { value: 'no', desc: '无' }
        ],
        intentionList: [
          { value: 0, desc: '无意向' },
          { value: 1, desc: '是' }
        ],
        optionList: [
          { value: 0, desc: '否' },
          { value: 1, desc: '是' }
        ],
        isAuditMap: [],
        date: [new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 3), new Date()],
        query: {
          checkType: '',
          subType: '',
          csmTypes: [],
          orgSNNo: '',
          imageName: 'all',
          checkDt: new Date().setDate(1),
          checkDtEnd: new Date(),
          provinceCode: '',
          cityCode: '',
          countryCode: '',
          repairStatus: '',
          // labelSource: [4],
          itemDetailIds: [],
          checkUserIdList: [],
          option: false,
          isAudit: 1
        },
        area: [],
        // addressProps: {
        //   lazy: true,
        //   checkStrictly: true,
        //   lazyLoad(node, resolve) {
        //     const { level, value } = node
        //     mergeAsyncFunc(selectAreaCode, { areaCode: value || 0 })
        //       .then((res) => {
        //         const nodes = res.data.map(item => ({
        //           value: item.areaCode,
        //           label: item.areaName,
        //           leaf: level >= 2
        //         }))
        //         resolve(nodes)
        //       })
        //       .catch(() => {
        //         node.loading = false
        //         node.loaded = false
        //       })
        //   }
        // },
        addressProps: [],
        roleTypeList: [],
        searchParams: {},
        tableData: {
          total: 0,
          data: []
        },
        selectRowIndex: null
      }
    },
    computed: {
      ...mapGetters(['orgList', 'exportDomain', '']),
      column: function() {
        return [
          {
            type: 'index'
          },
          // {
          //   type: 'selection'
          // },
          { label: '安检单号',
            width: 130,
            prop: 'checkId',
            className: 'checkId',
            render: (h, { row }) => ((row.warnLevel === 1 && (row.recheckStatus === 1 || row.recheckStatus === 2)) || (row.warnLevel === 2 && (row.repairStatus === 1 || row.repairStatus === 2))) ? (
              <div class='checkImg'>
                 <img src={row.warnLevel === 1 ? row.recheckStatus === 1 ? danger : row.recheckStatus === 2 ? passed : '' : row.warnLevel === 2 ? row.repairStatus === 1 ? danger2 : row.repairStatus === 2 ? fixed : '' : ''} alt={''}/>
                <el-link
                  size='mini'
                  underline={false}
                  onClick={() => this.openOrderInfo(row, '安检信息')}
                >
                  {row.checkId}
                </el-link>
              </div>
              ) : (
             <el-link
                  size='mini'
                  underline={false}
                  onClick={() => this.openOrderInfo(row, '安检信息')}
                >
                  {row.checkId}
                </el-link>
          )
          },
          {
            label: '客户编号',
            width: 110,
            prop: 'csmCode',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          },
          { label: '客户名称', prop: 'csmName' },
          {
            label: '客户类型',
            align: 'center',
            prop: 'csmType',
            render: (h, { row }) => (
            <span>
              {row.csmType &&
                formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc')}
            </span>
          )
          },
          {
            label: '用气性质',
            align: 'center',
            prop: 'subType',
            width: 110,
            render: (h, { row }) => (
            <span>
              {row.subType &&
                formatColumnMap(this.subTypeAllList, 'value', row.subType, 'label')}
            </span>
          )
          },
          { label: '客户地址', width: 150, prop: 'csmAddress' },
          { label: '所属机构', width: 150, prop: 'nearStationName' },
          {
            label: '安检单类别',
            align: 'center',
            prop: 'isAudit',
            render: (h, { row }) => (
            <span>
              {row.isAudit &&
                formatColumnMap(this.isAuditMap, 'value', row.isAudit, 'desc')}
            </span>
          )
          },
          { label: '标签',
            prop: 'label',
            render: (h, { row }) => (
            <span>
              {row.label &&
                formatColumnMap(this.labelMap, 'value', row.label, 'desc')}
            </span>
          )
          },
          {
            label: '安检类型',
            align: 'center',
            prop: 'checkType',
            render: (h, { row }) => (
            <span>
              {row.checkType &&
                formatColumnMap(this.checkTypeMap, 'value', row.checkType, 'desc')}
            </span>
          )
          },
          { label: '安检机构', width: 150, prop: 'orgName' },
          { label: '安检人', prop: 'checkUser' },
          { label: '稽/夜查员', prop: 'auditCheckUser' },
          {
            prop: 'driverName',
            label: '大车司机',
            showOverflowTooltip: true
          },
          {
            prop: 'escortName',
            label: '押运员',
            showOverflowTooltip: true
          },
          {
            label: '安检时间',
            width: 160,
            prop: 'checkDt',
            render: (h, { row }) => (
            <span>
              {row.checkDt && parseTime(row.checkDt, '{y}-{m}-{d} {h}:{i}:{s}')}
            </span>
          )
          },
          {
            label: '隐患等级',
            align: 'center',
            prop: 'warnLevel',
            width: 110,
            render: (h, { row }) =>
              row.warnLevel ? (
              <el-link underline={false} onClick={() => this.warnInfo(row)}>
                {formatColumnMap(this.warnLevelMap, 'value', row.warnLevel, 'desc')}
              </el-link>
                ) : (
              <span>
                {formatColumnMap(this.warnLevelMap, 'value', row.warnLevel, 'desc')}
              </span>
            )
          },
          { label: '隐患数',
            width: 80,
            prop: 'warnCount'
          },
          { label: '关联订单号',
            width: 110,
            prop: 'orderCode',
            render: (h, { row }) => (
                <el-link
                  size='mini'
                  underline={false}
                  onClick={() => this.openOrderDetail(row)}
                >
                  {row.orderCode}
                </el-link>
          )
          },
          // { label: '关联整改单',
          //   width: 130,
          //   prop: 'traceCode',
          //   render: (h, { row }) => (
          //       <el-link
          //         size='mini'
          //         underline={false}
          //         onClick={() => this.openOrderInfo(row, '整改详情')}
          //       >
          //         {row.traceCode}
          //       </el-link>
          // )
          // },
          // {
          //   label: '整改状态',
          //   align: 'center',
          //   prop: 'repairStatus',
          //   render: (h, { row }) => (
          //   <span>
          //     {row.repairStatus ? formatColumnMap(this.checkStatusMap, 'value', row.repairStatus, 'desc') : ''}
          //   </span>
          // )
          // },
          // {
          //   label: '最后整改时间',
          //   width: 160,
          //   prop: 'lastRepairDt',
          //   render: (h, { row }) => (
          //   <div>
          //     {(<span>{row.lastRepairDt && parseTime(row.lastRepairDt, '{y}-{m}-{d} {h}:{i}:{s}')}</span>)}
          //   </div>
          //   )
          // },
          { label: '关联复检单',
            width: 100,
            prop: 'recheckbillCode',
            render: (h, { row }) => (
                <el-link
                  size='mini'
                  underline={false}
                  onClick={() => this.openOrderInfo(row, '复检详情')}
                >
                  {row.recheckbillCode}
                </el-link>
          )
          },
          {
            label: '复检状态',
            prop: 'recheckStatus',
            render: (h, { row }) => (
            <span>
              { row.recheckStatus === 1 ? '待核查' : row.recheckStatus === 2 ? '通过' : row.recheckStatus === 3 ? '不通过' : row.recheckStatus === -1 ? '失效' : '' }
            </span>
          )
          },
          {
            label: '最后复检时间',
            width: 160,
            prop: 'lastRecheckDt',
            render: (h, { row }) => (
            <div>
              {(<span>{row.lastRecheckDt && parseTime(row.lastRecheckDt, '{y}-{m}-{d} {h}:{i}:{s}')}</span>)}
            </div>
            )
          },
          {
            label: '巡查结果',
            prop: 'auditingResult',
            render: (h, { row }) => (
            <span>
           { row.auditingResult === 1 ? '合格' : row.auditingResult === 2 ? '不合格' : '' }
            </span>
          )
          },
          {
            label: '可即查即改项',
            width: 120,
            prop: 'modificationCount',
            render: (h, { row }) => (
                <el-link
                  size='mini'
                  underline={false}
                  onClick={() => this.openDetails(row, 1)}
                >
                  {row.modificationCount}
                </el-link>
          ) },
          { label: '已整改', width: 70, prop: 'modificationEdCount' },
          {
            label: '是否有意向',
            width: 120,
            prop: 'isIntention',
            render: (h, { row }) => (
              row.isIntention === 2
                ? (<el-link
                  size='mini'
                  underline={false}
                  onClick={() => this.openDetails(row, 2)}
                >
                  {row.isIntention === 1 ? '无意向' : row.isIntention === 2 ? '有意向' : ''}
                </el-link>) : (
                  <span>{row.isIntention === 1 ? '无意向' : row.isIntention === 2 ? '有意向' : ''}</span>
                )
            ) }
        ]
      }
    },
    watch: {
      'query.orgSNNo': function(val) {
        this.queryGasCheckItem()
      },
      'query.checkType': function(val) {
        this.queryGasCheckItem()
      },
      'query.csmTypes': function(val) {
        this.queryGasCheckItem()
      }
    },
    async created() {
      await Promise.all([this.getTreeData(),
                         this.getdanger(),
                         this.queryOptionsMap(),
                         this.getCustomerLabelData()])
      const res1 = await querySubTypeMap({ })
      this.subTypeAllList = res1.data
      this.subTypeList = this.subTypeAllList
      this.$refs.lbTable.fetch({ currentPage: 1 })
    },
    methods: {
      async getdanger() {
        // presetDicQueryList
        const res = await queryRiskTrackMap()
        const data = JSON.parse(res.data.warnLevel) // 隐患等级
        if (data) {
          this.warnLevelMap = []
          data.forEach(item => {
            this.warnLevelMap.push({
              value: item.keyVal,
              desc: item.keyName
            })
          })
        }
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7, res8] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'GasAuditType' })
        ])
        this.calcTypeList = res1.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res2.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.paymentMethodMap = res2.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.orderStatusMap = res3.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res4.data // 订单类型
        this.payStatusMap = res5.data // 支付状态
        this.orderSourceMap = res6.data // 订单来源
        this.customerTypeMap = res7.data // 客户类型
        this.isAuditMap = res8.data // 安检单类别
        this.getTransactorList()
      },
      // 标签
      async getCustomerLabelData() {
        const res = await getCustomerLabel()
        if (res && res.data) {
          this.labelMap = res.data
        }
        const companyInfo = JSON.parse(sessionStorage.getItem('companyInfo'))
        // console.log('companyInfo', companyInfo)
        if (companyInfo.provinceCode && companyInfo.cityCode) {
          const res = await selectAreaCode({ areaCode: companyInfo.cityCode })
          this.addressProps = res.data.map(item => {
            return {
              value: item.areaCode,
              label: item.areaName
            }
          })
        }
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgSNNo = this.orgList && this.orgList[0].orgSNNo
        this.query.orgId = this.orgList && this.orgList[0].orgId
        this.selectTreeChange(this.orgList[0], 'first')
        // this.getCheckUser(this.query.orgId)
      },
      // 选择所属机构
      selectTreeChange(value, temp) {
        this.query.orgSNNo = value.orgSNNo
        this.query.orgId = value.orgId
        this.getCheckUser(value)
        if (!temp) {
          this.$refs.lbTable.fetch({ currentPage: 1 })
        }
      },
      // areaChange(area) {
      //   if (area.length === 1) {
      //     this.query.provinceCode = area[0]
      //     this.query.cityCode = ''
      //     this.query.countryCode = ''
      //   }
      //   if (area.length === 2) {
      //     this.query.provinceCode = area[0]
      //     this.query.cityCode = area[1]
      //     this.query.countryCode = ''
      //   }
      //   if (area.length === 3) {
      //     this.query.provinceCode = area[0]
      //     this.query.cityCode = area[1]
      //     this.query.countryCode = area[2]
      //   }
      //   if (area.length === 0) {
      //     this.query.provinceCode = ''
      //     this.query.cityCode = ''
      //     this.query.countryCode = ''
      //   }
      //   console.log(area)
      // },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            // if (obj[key] !== '') {
            if (key === 'csmTypes') {
              if (obj[key] !== '') {
                query[key] = [obj[key]]
              } else {
                query[key] = obj[key]
              }
            } else {
              query[key] = obj[key]
            }
            // }
          }
        }
        query.orgId = this.query.option ? 0 : this.query.orgId
        query.isAudit = !this.query.isAudit ? -1 : this.query.isAudit
        return query
      },

      async fetchData({ currentPage, pageSize }) {
        const query = await this.getQuery()
        query.pageIndex = currentPage
        query.pageSize = pageSize
        if (this.param) {
          query[this.qtype] = this.param
        }
        if (query.checkDt && query.checkDtEnd) {
          let checkDt = parseTime(query.checkDt, '{y}-{m}-{d} {h}:{i}:{s}')
          let checkDtEnd = parseTime(query.checkDtEnd, '{y}-{m}-{d} {h}:{i}:{s}')
          checkDt = checkDt.split(' ')
          checkDtEnd = checkDtEnd.split(' ')
          checkDt[1] = '00:00:00'
          checkDtEnd[1] = '00:00:00'
          checkDt = checkDt.join(' ')
          checkDtEnd = checkDtEnd.join(' ')
          query.checkDt = checkDt
          query.checkDtEnd = checkDtEnd
        }
        if (query.warnLevel === 0) query.warnLevel = -1
        const res = await gasCheckBillQueryList(query)
        this.searchParams = query
        console.log(this.searchParams)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      radioChange(value) {
        this.query.imageName = value
        this.$refs.lbTable.fetch()
      },
      // 安检人
      async getCheckUser(val) {
        this.query.checkUserIdList = []
        const res = await csDeliverUserList({
          deliveryOrgId: val.orgId,
          deliveryOrgSNNo: val.orgSNNo,
          utypeList: [2048, 16384]
        })
        this.checkUserMap = res.data
      },
      queryGasCheckItem() {
        let val
        if (this.query.csmTypes && this.query.csmTypes.length) {
          val = this.query.csmTypes.reduce((prev, cur, index, array) => {
            return prev + cur
          })
        }
        gasCheckItemList({
          orgSNNo: this.query.orgSNNo,
          csmType: val,
          checkType: this.query.checkType
        }).then((res) => {
          const gasCheckItemArray = res.data
          gasCheckItemArray.map((item) => {
            item.detailList.map((item2) => {
              item2.label = item2.itemDetailName
              item2.value = item2.itemDetailId
            })
            item.children = item.detailList
            item.label = item.itemName
            item.value = item.itemId
          })
          if (!this.query.csmTypes.length) {
            this.gasCheckItemArray = []
          } else {
            this.gasCheckItemArray = gasCheckItemArray
          }
        })
      },
      changType(val) {
        this.query.subType = ''
        this.subTypeList = []
        if (!val.length) {
          this.gasCheckItemArray = []
          this.subTypeList = this.subTypeAllList
        }
        this.getSubTypeMap(val)
      },
      async getSubTypeMap(csmType) {
        const res = await querySubTypeMap({ csmType })
        this.subTypeList = res.data
      },
      changeChecktype() {
        if (!this.query.csmTypes.length) this.gasCheckItemArray = []
      },
      revokeExamine(row) {
        this.$confirm(`本操作将清空该地址的最后一次安检时间，是否继续？`, '操作提示', {
          type: 'warning'
        }).then(() => {
          gasCheckBillReverse({
            checkIds: row.checkId
          }).then((res) => {
            if (res.success) {
              this.$message({
                message: '操作成功!',
                type: 'success'
              })
              this.search()
            } else {
              this.$message({
                message: '操作失败！',
                type: 'error'
              })
            }
          })
        })
      },
      // 批量审核
      batchExamine() {
        const multipleSelection = this.multipleSelection
        if (multipleSelection.length < 1) {
          this.$alert('请至少选择一个安检单进行批量审核！', '提示', {
            type: 'info',
            confirmButtonText: '确定'
          })
          return
        }
        this.$refs.batchExamine.open(multipleSelection)
      },
      // 隐患详情
      warnInfo(row) {
        this.$refs.rectification.open(row)
      },
      // 导出
      batchExp() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.splice(18, 0, { label: '隐患内容', prop: 'warnLevelName' })
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          // const paramInfo = _this._getQuery(params)
          params.checkDt = new Date(params.checkDt)
          params.checkDtEnd = new Date(params.checkDtEnd)
          gasCheckBillExport({
            paramInfo: params,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 安检单详情
      async openOrderInfo(row, type) {
        const r = JSON.parse(JSON.stringify(row))
        await this.$refs.securityOrderInfo.open(r, type)
      },
      // async openOrderExamine(row) {
      //   await this.$refs.securityOrderInfo.open(row, 'examine')
      //   this.$refs.lbTable.fetch()
      // },
      async scoresMerge() {},
      async infoCircul() {},
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      reset() {
        this.$refs.form.resetFields()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      async getQuery() {
        const query = { ...this._getQuery(this.query) }
        if (this.date && this.date.length > 0) {
          query.checkDt = this.date[0]
          query.checkDtEnd = this.date[1]
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 93) {
            this.$message.error('选择时间条件相差不能超过3个月')
            return
          }
        }
        return query
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 打开关联订单
      async openOrderDetail(row) {
        if (row.billType === 2) {
          await this.$refs.repairDetail.open({ repairCode: row.orderCode, ...row })
          return
        }
        await this.$refs.orderDetail.open(row, true)
      },
      async openDetails(row, type) {
        if (type === 1) {
          await this.$refs.checkandFix.open(row)
        }
        if (type === 2) {
          await this.$refs.isIntention.open(row)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  .el-radio {
    margin-right: 15px;
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: flex-start;
}

.check-lbTable {
  & /deep/ .el-table .checkId {
    padding: 0;
    // .cell {
    //   padding: 0;
    // }
    .checkImg {
      display: flex;
      margin-left: -9px;
      img {
        width: 30px;
        height: auto;
      }
    }
  }
}

</style>
